package util.concurrent.delayqueue;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 6/7/2022 8:56 PM
 */
public class DelayDemo implements Delayed {

    /**
     * 延迟时间
     */
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Long time;

    /**
     * 任务名称
     */
    private String name;


    public DelayDemo(Long time, String name, TimeUnit unit) {
        this.time = System.currentTimeMillis() + (time > 0 ? unit.toMillis(time) : 0);
        this.name = name;
    }

    /**
     * 获取延迟时间
     *
     * @param unit unit
     * @return long
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return time - System.currentTimeMillis();
    }

    /**
     * 对延迟队列中的元素进行排序
     *
     * @param o
     * @return int
     */
    @Override
    public int compareTo(Delayed o) {
        DelayDemo delayDemo = (DelayDemo) o;
        return time.compareTo(delayDemo.getTime());
    }

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
